import {Component} from '@angular/core';
import {AlertController, LoadingController, NavController, Platform, ToastController} from 'ionic-angular';
import {NotifyPage} from "./notify/notify";
import {SystemService} from "../service/SystemService";
import {NotifyItemPage} from "./notify-item/notify-item";
import {ApplyListAPage} from "../apply/applyList";
import {ExamineApprovePage} from "../examine/examineApprove";
import {UserManager} from "../../framework/manager/UserManager";
import {GuidePage} from "../guide/guide";
import {IndexQueryPage} from "../index-query/index-query";
import {WaitCheckPage} from "./wait-check/wait-check";
import {BasePage} from "../BasePage";
import {Log} from "../../framework/utils/Log";
import { Observable }from 'rxjs/Rx';
import {MyExpensesPage} from "./my-expenses/my-expenses";
import {ApplyTabPage} from "../apply/apply-tab/apply-tab";
import {ApplyStoreSLS} from "../apply/applyStoreSLS";
import {ZxInformationPage} from "../examineApprove/zxInformation/zxInformation";
import {ZjInformationPage} from "../examineApprove/zjInformation/zjInformation";
import {HtqdInformationPage} from "../examineApprove/htqdInformation/htqdInformation";
import {HtbgInformationPage} from "../examineApprove/htbgInformation/htbgInformation";
import {CgInformationPage} from "../examineApprove/cgInformation/cgInformation";

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: [SystemService]

})
export class HomePage extends BasePage{
    private static TAG:string="HomePage";
    navData: any = [
       // {title: '我的报销', src: './assets/imgs/icon_baoxiaoshenqing.png', color: '#20c7a2'},
        {title: '通知公告', src: './assets/imgs/tongzhi.png', color: '#f0c330'},
        //{title: '预算进度', src: './assets/imgs/yusuanjindu.png', color: '#679cdd'},
        {title: '支出细则', src: './assets/imgs/zhichuxijie.png', color: '#fc6030'},
    ];

    notifyList: any = [];
    private _userId: any;
    private _unitId: any;
    private pageCount: number = 1;
    private pageRowCount: number = Math.ceil(window.innerHeight / 60);
    private isEnd:boolean = false;
    private infinite: any;

    sysMsg:string;
    constructor(public navCtrl: NavController, public sys: SystemService, public platform: Platform,
    public loadingCtrl: LoadingController,
    public toastCtrl: ToastController,
    public alertCtrl: AlertController) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl);
        this._unitId = UserManager.getInstance().user.unitId;
        this._userId = UserManager.getInstance().user.userId;

        setTimeout(() => {
           // let scrollHeight = window.innerHeight - 44 - 120 - 10 - 49;
           // let scrollHeight = window.outerHeight - 210;
            //document.getElementsByClassName("scroll-content")[0]['style'].setProperty('height', scrollHeight + 'px');
           // document.getElementById("nofityScroll").style.height= scrollHeight+'px';

        }, 100);

    }
    ngOnInit() {
        // 监听页面改变
        Observable.fromEvent(window,'resize').subscribe((event) => {
            // 操作
            let scrollHeight = window.outerHeight - 210;
            document.getElementById("nofityScroll").style.height= scrollHeight+'px';

        });
    }
    ionViewDidEnter() {
        // this.tabName('待办事项', 0);
    }
    ionViewWillEnter(){
        Log.w(HomePage.TAG, 'ionViewWillEnter HomePage');
        this.notifyList =[];
        this.getToDoInfo();
    }
    //获取系统消息
    getSysMsgList(){
        this.sys.getSysMsgUrl({YongHuBH: this._userId}).subscribe((res:any)=>{
            Log.printObj(HomePage.TAG,'getSysMsgUrl res ==',res);
            if(res.msgCode=="1"){
                this.sysMsg=res.list;
            }
        },error=>{

        })
    }
    //请求公告列表
    getNotifyInfo() {
        let notifyInfo: any = {
            DanWeiBH: this._unitId,
            YongHuBH: this._userId,
            RowNum: 5
        };
        this.sys.getNotifyList(notifyInfo)
            .subscribe((res: any) => {
                if (res.msgCode == '1') {
                    this.notifyList = res.list;
                }

            }, error => {
            });
    }

    //请求首页待办
    getToDoInfo() {
        this.showLoading(true, '请稍后');
        let year = UserManager.getInstance().user.year;
        let toDoInfo: any = {
            DanWeiBH: this._unitId,
            YongHuBH: this._userId,
            PageRow: this.pageCount,
            RowNum: this.pageRowCount,
            NianDu: year
        };
        this.sys.getToDoList(toDoInfo).subscribe((res: any) => {
            if (res.msgCode == '1' && res.list) {
                //this.notifyList.push(...res.list);
                this.notifyList = this.notifyList.concat(res.list);
            } else {
                this.isEnd = true;
            }
            this.showLoading(false, '请稍后');
        }, error => {
        });
    }

    navItem(name) {
        switch (name) {
            case '我的报销':
                this.navCtrl.push(MyExpensesPage);
                break;
            case '通知公告':
                this.navCtrl.push(NotifyPage);
                break;
            case '预算进度':
                this.navCtrl.push(IndexQueryPage);
                break;
            case '待办审批':
                this.navCtrl.push(WaitCheckPage);
                break;
            case '支出细则':
                this.navCtrl.push(GuidePage);
                break;
        }
    }




    notifyHandler(item,index) {
        ApplyStoreSLS.getInstance().destroy();
        if ('0' == item.LeiXing) {
            let id = item.BianHao;
            this.notifyList.splice(index,1);
            this.navCtrl.push(NotifyItemPage, {'id': id});
        } else if ('1' == item.LeiXing) {
            item['DanJuBH'] = item.BianHao;
            this.navCtrl.push(ExamineApprovePage, {data: item, type: '1'});
        } else if ('2' == item.LeiXing) {
            let data = {BianHao: item.BianHao};
            this.sys.updateSysMsgState(data).subscribe((res: any) => {
                if (res.msgCode == '1') {
                    this.notifyList.splice(index,1);
                }
            }, error => {});
        } else if ('3' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
            this.navCtrl.push(ApplyTabPage,{data:item,type:"4"})
        }else if ('4' == item.LeiXing || '5' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
            this.getZxCheckDetail(item,'1','2');
        } else if ('6' == item.LeiXing ||'7' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
           this. getZjCheckDetail(item,'1','3');
        }else if ('8' == item.LeiXing || '12' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
            this. getCgxqdbspDetail(item,'1','4');
        }else if ('9' == item.LeiXing || '10' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
            this. getHtgldHbspDetail(item,'1','5');
        }else if ('11' == item.LeiXing || '13' == item.LeiXing) {
            UserManager.getInstance().user.djId = item.DanJuBH;
            item['DanJuBH'] = item.BianHao;
            this. getHtgldbspBgdetail(item,'1','6');
        }
    }
    //资金申请审批
    getZjCheckDetail(_d,type,spType) {
        let data: any = {
            BianHao: _d.DanJuBH,
            LiuChengId: _d.LiuChengId,
            RenWuID: _d.RenWuID,
            DangQianJD: _d.DangQianJD
        };
        this.sys.dbspzjDetails(data).subscribe((res: any) => {
            Log.printObj(HomePage.TAG, '资金待审详细printObj==', res);
            if (res.msgCode == '1') {
                this.navCtrl.push(ZjInformationPage, { data: res,type:type,_d:data,spType:spType})
            } else {
                this.showError('数据请求失败');
            }
        }, error => {
            this.showError('数据请求失败');
        })
    }
    //执行审批
    getZxCheckDetail(_d,type,spType) {
        let data: any = {
            BianHao: _d.DanJuBH,
            LiuChengId: _d.LiuChengId,
            RenWuID: _d.RenWuID,
            DangQianJD: _d.DangQianJD
        };
         this.sys.dbspzxDetails(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                //this.danJuInfo =this.detailInfo.DanJuXX.ShenQingDH;
                Log.printObj(HomePage.TAG, "执行待审详细data==",res);
                this.navCtrl.push(ZxInformationPage, { data: res,type:type,_d:data,spType:spType})
            } else {
                this.showError('数据请求失败');
            }

        }, error => {
            this.showError('数据请求失败');
        })
    }
    /**
     * 审批详情(合同签订)
     * */
    getHtgldHbspDetail(_d,type,spType){
        let data: any = {
            BianHao: _d.DanJuBH,
            LiuChengId: _d.LiuChengId,
            RenWuID: _d.RenWuID,
            DangQianJD: _d.DangQianJD
        };
        this.sys.htgldbspDetail(data).subscribe((res: any) => {
            Log.printObj(HomePage.TAG, '审批详情(合同签订)printObj==', res);
            if (res.msgCode === '1') {
                this.navCtrl.push(HtqdInformationPage, { data: res,type:type,_d:data,spType:spType})
            } else {
                this.showError('数据请求失败');
            }
        }, error => {
            this.showError('数据请求失败');
        })
    }
    /**
     * 审批详情(合同变更)
     * */
    getHtgldbspBgdetail(_d,type,spType){
        let data: any = {
            BianHao: _d.DanJuBH,
            LiuChengId: _d.LiuChengId,
            RenWuID: _d.RenWuID,
            DangQianJD: _d.DangQianJD
        };
        this.sys.htgldbspBgdetail(data).subscribe((res: any) => {
            Log.printObj(HomePage.TAG, '审批详情printObj==', res);
            if (res.msgCode == '1') {
                this.navCtrl.push(HtbgInformationPage, { data: res,type:type,_d:data,spType:spType})
            } else {
                this.showError('数据请求失败');
            }
        }, error => {
            this.showError('数据请求失败');
        })
    }
    /**
     * 审批详情(采购需求)
     * */
    getCgxqdbspDetail(_d,type,spType){
        let data: any = {
            BianHao: _d.DanJuBH,
            LiuChengId: _d.LiuChengId,
            RenWuID: _d.RenWuID,
            DangQianJD: _d.DangQianJD
        };
        this.sys.cgxqdbspDetail(data).subscribe((res: any) => {
            Log.printObj(HomePage.TAG, '审批详情(采购需求)printObj==', res);
            if (res.msgCode == '1') {
                this.navCtrl.push(CgInformationPage, { data: res,type:type,_d:data,spType:spType})
            } else {
                this.showError('数据请求失败');
            }
        }, error => {
            this.showError('数据请求失败');
        })
    }
    //下滑动加载数据
    doInfinite(infiniteScroll) {
        setTimeout(() => {
            console.log('加载完成后，关闭刷新');
            infiniteScroll.complete();
            //this.showError("加载成功");
            //页数
            this.pageCount++;
            this.getToDoInfo();
            if(infiniteScroll){
                infiniteScroll.complete();
                if(this.isEnd){
                    //如果都加载完成的情况，就直接 disable ，移除上拉加载
                    this.infinite = infiniteScroll;
                    infiniteScroll.enable(false);
                    this.showLoading(false, '请稍后');
                   // this.showError("已加载所有");
                }
            }
        }, 300);
    }

    doRefresh(refresher) {
        console.log('Begin async operation');
        setTimeout(() => {
            //this.showLoading(true, '请稍后');
            this.isEnd = false;
            this.pageCount = 1;
            this.notifyList=[]
            this.getToDoInfo();
            // let toDoInfo: any = {
            //     DanWeiBH: this._unitId,
            //     YongHuBH: this._userId,
            //     PageRow: this.pageCount,
            //     RowNum: this.pageRowCount
            // };
            // this.sys.getToDoList(toDoInfo).subscribe((res: any) => {
            //     if (res.msgCode == '1') {
            //         this.notifyList = res.list;
            //     } else {
            //         this.isEnd = true;
            //     }
            //     //this.showLoading(false, '请稍后');
            // }, error => {
            // });
            console.log('Async operation has ended');
            refresher.complete();
            if(this.infinite){
                this.infinite.enable(true);
            }
        }, 500);
    }
}
